<template>
  <div class="dashboard-container">
    <!-- 欢迎信息 -->
    <el-card class="welcome-card">
      <div class="welcome-content">
        <div class="welcome-text">
          <h2>欢迎回来，{{ userStore.userInfo?.name }}</h2>
          <p>{{ getWelcomeMessage() }}</p>
        </div>
        <div class="welcome-info">
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="info-item">
                <el-icon class="info-icon"><Calendar /></el-icon>
                <div class="info-content">
                  <p class="info-label">今日日期</p>
                  <p class="info-value">{{ currentDate }}</p>
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <el-icon class="info-icon"><Clock /></el-icon>
                <div class="info-content">
                  <p class="info-label">当前学期</p>
                  <p class="info-value">2023-2024 第二学期</p>
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <el-icon class="info-icon"><Reading /></el-icon>
                <div class="info-content">
                  <p class="info-label" v-if="userStore.isStudent">已选课程</p>
                  <p class="info-label" v-else-if="userStore.isTeacher">所教课程</p>
                  <p class="info-value" v-if="userStore.isStudent">{{ courseStore.selectedCourses.length }} 门</p>
                  <p class="info-value" v-else-if="userStore.isTeacher">{{ teacherCourses.length }} 门</p>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-card>

    <el-row :gutter="20" class="dashboard-row">
      <!-- 待办事项 -->
      <el-col :span="16">
        <el-card class="dashboard-card">
          <template #header>
            <div class="card-header">
              <h3>今日课程</h3>
              <el-button type="primary" text @click="viewAllCourses">查看所有</el-button>
            </div>
          </template>
          <div v-if="todayCourses.length > 0">
            <div v-for="course in todayCourses" :key="course.id" class="course-item">
              <div class="course-time">
                {{ getScheduleTime(course) }}
              </div>
              <div class="course-content">
                <h4>{{ course.name }}</h4>
                <p>{{ course.teacher }} | {{ getLocation(course) }}</p>
              </div>
              <el-tag v-if="isCurrentCourse(course)" type="success">正在进行</el-tag>
              <el-tag v-else-if="isUpcomingCourse(course)" type="warning">即将开始</el-tag>
              <el-tag v-else-if="isCompletedCourse(course)" type="info">已结束</el-tag>
            </div>
          </div>
          <el-empty v-else description="今日没有课程安排" />
        </el-card>
      </el-col>

      <!-- 公告栏 -->
      <el-col :span="8">
        <el-card class="dashboard-card">
          <template #header>
            <div class="card-header">
              <h3>公告栏</h3>
            </div>
          </template>
          <div class="notice-list">
            <div v-for="(notice, index) in notices" :key="index" class="notice-item">
              <div class="notice-title">{{ notice.title }}</div>
              <div class="notice-time">{{ notice.time }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="dashboard-row">
      <!-- 课程数据统计 -->
      <el-col :span="12">
        <el-card class="dashboard-card">
          <template #header>
            <div class="card-header">
              <h3>课程统计</h3>
            </div>
          </template>
          <el-row :gutter="20" class="stat-row">
            <el-col :span="8">
              <div class="stat-item">
                <div class="stat-value">{{ courseStats.total }}</div>
                <div class="stat-label">总课程数</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-item">
                <div class="stat-value">{{ courseStats.required }}</div>
                <div class="stat-label">必修课程</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-item">
                <div class="stat-value">{{ courseStats.elective }}</div>
                <div class="stat-label">选修课程</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>

      <!-- 快速链接 -->
      <el-col :span="12">
        <el-card class="dashboard-card">
          <template #header>
            <div class="card-header">
              <h3>快速操作</h3>
            </div>
          </template>
          <div class="quick-links">
            <el-button v-if="userStore.isStudent" type="primary" @click="$router.push('/course-selection')">
              <el-icon><Plus /></el-icon>选择课程
            </el-button>
            <el-button v-if="userStore.isStudent" type="info" @click="$router.push('/schedule')">
              <el-icon><Calendar /></el-icon>查看课表
            </el-button>
            <el-button v-if="userStore.isTeacher" type="success" @click="$router.push('/course-manage')">
              <el-icon><Edit /></el-icon>管理课程
            </el-button>
            <el-button v-if="userStore.isAdmin" type="warning" @click="$router.push('/admin')">
              <el-icon><Setting /></el-icon>管理系统
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { useCourseStore } from '../stores/course'

const router = useRouter()
const userStore = useUserStore()
const courseStore = useCourseStore()

// 当前日期
const currentDate = computed(() => {
  const date = new Date()
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
})

// 当前星期几（1-7）
const currentDay = computed(() => {
  const day = new Date().getDay()
  return day === 0 ? 7 : day // 将周日的0转换为7
})

// 当前时间（小时:分钟）
const currentTime = ref('')
setInterval(() => {
  const date = new Date()
  currentTime.value = `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}, 1000)

// 教师所教课程
const teacherCourses = computed(() => {
  if (!userStore.isTeacher) return []
  // 筛选当前教师所教授的课程
  // 这里假设用户登录后，userInfo中包含了name字段，用于匹配课程的teacher字段
  return courseStore.courses.filter(course => 
    course.teacher && course.teacher.includes(userStore.userInfo?.name)
  )
})

// 今日课程（针对学生和教师做区分）
const todayCourses = computed(() => {
  if (userStore.isStudent) {
    if (!courseStore.selectedCourses.length) return []
    
    return courseStore.selectedCourses
      .filter(course => 
        course.schedule.some(schedule => schedule.day === currentDay.value)
      )
      .sort((a, b) => {
        const aTime = a.schedule.find(s => s.day === currentDay.value)?.startTime || ''
        const bTime = b.schedule.find(s => s.day === currentDay.value)?.startTime || ''
        return aTime.localeCompare(bTime)
      })
  } else if (userStore.isTeacher) {
    if (!teacherCourses.value.length) return []
    
    return teacherCourses.value
      .filter(course => 
        course.schedule.some(schedule => schedule.day === currentDay.value)
      )
      .sort((a, b) => {
        const aTime = a.schedule.find(s => s.day === currentDay.value)?.startTime || ''
        const bTime = b.schedule.find(s => s.day === currentDay.value)?.startTime || ''
        return aTime.localeCompare(bTime)
      })
  }
  
  return []
})

// 模拟公告数据
const notices = ref([
  { title: '2023-2024学年第二学期选课通知', time: '2024-02-20' },
  { title: '关于调整部分课程时间安排的通知', time: '2024-02-25' },
  { title: '期中考试时间安排', time: '2024-03-10' },
  { title: '五一假期课程调整通知', time: '2024-04-20' },
])

// 课程统计数据
const courseStats = computed(() => {
  const total = courseStore.courses.length
  const required = courseStore.courses.filter(c => c.type === '必修课').length
  const elective = total - required
  
  return { total, required, elective }
})

// 获取欢迎信息
const getWelcomeMessage = () => {
  const hour = new Date().getHours()
  
  if (hour < 6) return '夜深了，请注意休息。'
  if (hour < 12) return '早上好，祝您有个愉快的一天！'
  if (hour < 14) return '中午好，记得休息一下哦！'
  if (hour < 18) return '下午好，继续加油！'
  return '晚上好，今天也辛苦了！'
}

// 获取课程时间段
const getScheduleTime = (course) => {
  const schedule = course.schedule.find(s => s.day === currentDay.value)
  if (schedule) {
    return `${schedule.startTime} - ${schedule.endTime}`
  }
  return ''
}

// 获取课程地点
const getLocation = (course) => {
  const schedule = course.schedule.find(s => s.day === currentDay.value)
  return schedule ? schedule.location : ''
}

// 判断课程状态
const isCurrentCourse = (course) => {
  const schedule = course.schedule.find(s => s.day === currentDay.value)
  if (!schedule) return false
  
  return currentTime.value >= schedule.startTime && currentTime.value <= schedule.endTime
}

const isUpcomingCourse = (course) => {
  const schedule = course.schedule.find(s => s.day === currentDay.value)
  if (!schedule) return false
  
  return currentTime.value < schedule.startTime
}

const isCompletedCourse = (course) => {
  const schedule = course.schedule.find(s => s.day === currentDay.value)
  if (!schedule) return false
  
  return currentTime.value > schedule.endTime
}

// 查看所有课程
const viewAllCourses = () => {
  router.push('/schedule')
}

// 页面加载时初始化当前时间
onMounted(() => {
  const date = new Date()
  currentTime.value = `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
})
</script>

<style scoped>
.dashboard-container {
  padding: 0 10px;
}

.dashboard-row {
  margin-bottom: 20px;
}

.welcome-card {
  margin-bottom: 20px;
  background: linear-gradient(to right, #1e88e5, #3949ab);
  color: white;
}

.welcome-content {
  padding: 10px;
}

.welcome-text h2 {
  font-size: 24px;
  margin-bottom: 10px;
}

.welcome-text p {
  font-size: 16px;
  margin-bottom: 20px;
  opacity: 0.9;
}

.welcome-info {
  margin-top: 20px;
}

.info-item {
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  padding: 15px;
}

.info-icon {
  font-size: 24px;
  margin-right: 10px;
}

.info-label {
  font-size: 12px;
  opacity: 0.8;
  margin-bottom: 5px;
}

.info-value {
  font-size: 16px;
  font-weight: bold;
}

.dashboard-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
}

.course-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #ebeef5;
}

.course-item:last-child {
  border-bottom: none;
}

.course-time {
  min-width: 120px;
  font-weight: bold;
  color: #409eff;
}

.course-content {
  flex: 1;
  margin: 0 15px;
}

.course-content h4 {
  margin: 0 0 5px 0;
}

.course-content p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.notice-list {
  max-height: 300px;
  overflow-y: auto;
}

.notice-item {
  padding: 10px 0;
  border-bottom: 1px solid #ebeef5;
}

.notice-item:last-child {
  border-bottom: none;
}

.notice-title {
  font-weight: 500;
  margin-bottom: 5px;
}

.notice-time {
  font-size: 12px;
  color: #909399;
}

.stat-row {
  text-align: center;
}

.stat-item {
  padding: 15px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.quick-links {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
</style> 